package c3g;

import com.google.protobuf.DescriptorProtos;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class Descriptorfile {
    private String outputfile;
    private String packge;
    private String classname;
    //生成Descriptor文件
    public void buildDescriptorfile(File file2,Port port,Config config) throws IOException, InterruptedException {

        String a=file2.getCanonicalPath();
        String protocCMD = config.getCMD()+" --descriptor_set_out="+config.getSet_out()+port.getFilename()+".description "+a+" --proto_path=C://";
        Process process = Runtime.getRuntime().exec(protocCMD); //运行cmd生成出descriptor文件
        process.waitFor();
    }
    //读取Descriptor文件
    public void readDescriptorfile(Config config,Port port) throws IOException {
        DescriptorProtos.FileDescriptorSet descriptorSet = DescriptorProtos.FileDescriptorSet.parseFrom(new FileInputStream(config.getSet_out() +port.getFilename() + ".description"));
        port.getlist().clear();              //清空缓存
        for (DescriptorProtos.FileDescriptorProto fdp : descriptorSet.getFileList()) {
            //读取c2g名和文件名
            this.packge=fdp.getOptions().getJavaPackage();           //c2g
            this.classname=fdp.getOptions().getJavaOuterClassname(); //文件名
            List<DescriptorProtos.DescriptorProto> pp =fdp.getMessageTypeList();
            for(DescriptorProtos.DescriptorProto descriptorProto : pp){
                List<DescriptorProtos.FieldDescriptorProto>  tt=descriptorProto.getFieldList();
                for(DescriptorProtos.FieldDescriptorProto des : tt){
                    //读取Type、optionals、setlabels存入ArrayList<Item> list中
                    Item item =new Item();                                           //每次循环都new一个Item对象
                    String type =des.getType().toString().toLowerCase(Locale.ROOT);     //格式化type和label
                    String label =des.getLabel().toString().toLowerCase(Locale.ROOT);
                    item.setTypes(type.substring(type.indexOf("_")+1));                 //将数据存入item中
                    item.setoptionals(des.getName());
                    item.setLabels(label.substring(type.indexOf("_")+2));
                    port.getlist().add(item);                                          //将对象存入list
                }
            }
        }
    }

    public void setOutputfile(String outputfile){

        this.outputfile =outputfile;
    }
    public String getOutputfile() {

        return outputfile;
    }
    public String getpackge() {

        return packge;
    }
    public void setpackge(String packge) {

        this.packge= packge;
    }
    public String getclassname() {

        return classname;
    }
    public void setclassname(String classname) {

        this.classname =classname;
    }
}
